require 'xmpp4r'
require 'xmpp4r/muc/helper/simplemucclient'
require 'xmpp4r/version/helper/simpleresponder'
require 'cmdlet'
$VERSION = "0.02"
class Chat
  include Jabber
  def initialize(jid,password,conf)
    @conf = conf
    @confid = conf.gsub(/\/.+$/,'')
    @botnick = conf.gsub(/^.*\//,'')
    @comm = Execute.new
    begin
      connect jid,password
    rescue
      puts "Connection failed..."
      exit
    end
  end

  def connect (jid,password)
    @cl = Jabber::Client.new(Jabber::JID.new(jid))
    @cl.connect
    @cl.auth(password)
    set_version
    set_queries
  end

  def set_queries
    @cl.add_iq_callback { |iq|
      # Filter for version query results
      if (iq.type == :result) && iq.query.kind_of?(Jabber::Version::IqQueryVersion)
        puts "Version query result from #{iq.from}"
        # Keep track of results per JID
        # Print details
        os = iq.query.os ? iq.query.os.to_s : 'unknown'
        from = iq.from.to_s.sub(/^.+\//,'')
        puts from
        @mconf.say "#{from} has #{iq.query.iname.to_s}-#{iq.query.version.to_s}@#{os}"
        sleep 1.4
      end
    }
  end

  def join
    @mconf = Jabber::MUC::SimpleMUCClient.new(@cl)
    @mconf.on_message { |time,nick,text|
      #we don't want to react on history messages, so we ignore messages with time stamps
      #on the other hand history is disabled by default.
      unless time || nick==@botnick
        reply_to nick,text
      end
    }
    @mconf.on_private_message { |time,nick,text|
      unless time || nick==@botnick
        reply_to nick,text, {:private => "true"}
      end
    }
    @mconf.on_join {|time,nickname|
      @comm.do_version nickname,@confid,@cl if @comm.commands[:version][:on_join]
    }

    #and finaly go to join :)


    begin
      @mconf.join @conf, {:history => false}
    rescue
      puts "Can't join conference, sorry..."
      exit
    end

  end

  def reply_to nick,text,opts = {}
    result = @comm.run_command text,@confid,@cl
    (say result,nick; return) if opts[:private]
    say result unless result.empty?
 end

  def say str,nick=nil
    (@mconf.say str.force_encoding("utf-8"),nick.force_encoding("utf-8");return) if nick
    @mconf.say str
  end

  def set_version os=nil
    begin
      os ||= `uname -ro`.chomp
    rescue
      os = "Microsoft Windows 7 (build 7600)"
    end
    Jabber::Version::SimpleResponder.new(@cl,"nagisa",$VERSION,os)
  end
  #The only public methods are say and join
  private :set_version, :reply_to, :set_queries, :connect
end


